package org.example.timertask;

import io.netty.util.HashedWheelTimer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务启动配置抽象类
 */
public abstract class BaseTimerTaskStartConfiguration<T> {


    protected  HashedWheelTimer hashedWheelTimer;
    protected ThreadPoolTaskExecutor taskExecutor;
    protected TimerEndProcessor<T> endProcessor;
    protected TimerStartProcessor<T> startProcessor;
    public void startConfig(HashedWheelTimer hashedWheelTimer,
                            ThreadPoolTaskExecutor taskExecutor) {
        this.hashedWheelTimer = hashedWheelTimer;
        this.taskExecutor = taskExecutor;
        configProcessor();

        LocalDateTime now = LocalDateTime.now();
        // 获取未开始的
        List<T> unStartList = listUnStartInfo();
        //获取未结束的
        List<T> startingList = listUnEndInfo();

        //初始化将未开始的加入延时任务
        unStartList
                .stream()
                .filter(item -> isUnStart(now, item))
                .forEach(item -> addOnTimerTask(now, item));

        //初始化将未下架的活动加入延时任务
        startingList
                .stream()
                .filter(item -> isStarting(now, item))
                .forEach(item -> addOffTomerTask(now, item));

        //补偿机制
        taskExecutor.execute(() -> {
            unStartList
                    .stream()
                    .filter(item -> isStarting(now,item))
                    .forEach(startProcessor::unStartToStarting);
            unStartList
                    .stream()
                    .filter(item -> isEnded(now, item))
                    .forEach(endProcessor::unStartToEnd);
            startingList
                    .stream()
                    .filter(item -> isEnded(now, item))
                    .forEach(endProcessor::startingToEnd);
        });
    }

    /**
     * 配置处理器
     */
    public abstract void configProcessor();

    /**
     * 获取状态为未开始的数据集合
     */
    public abstract List<T> listUnStartInfo();

    /**
     * 获取状态为未结束的数据集合
     */
    public abstract List<T> listUnEndInfo();

    /**
     * 未开始的时间判断标准
     */
    public abstract boolean isUnStart(LocalDateTime now, T item) ;
    /**
     * 进行中的时间判断标准
     */
    public abstract boolean isStarting(LocalDateTime now, T item) ;
    /**
     * 已结束的时间判断标准
     */
    public abstract boolean isEnded(LocalDateTime now, T item);
    /**
     * 添加开始时间轮任务
     */
    public abstract void addOnTimerTask(LocalDateTime now, T item);
    /**
     * 添加结束时间轮任务
     */
    public abstract void addOffTomerTask(LocalDateTime now, T item);


}
